package org.pvt.gui;

import android.text.InputFilter;
import android.text.Spanned;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Pavel Talanov
 *         <p/>
 *         from: http://stackoverflow.com/a/8272212
 */
public final class DecimalDigitsInputFilter implements InputFilter {

    public static int DIGITS_BEFORE_POINT = 5;
    public static int DIGITS_AFTER_POINT = 2;

    private final Pattern mPattern;

    public DecimalDigitsInputFilter() {
        mPattern = Pattern.compile("[0-9]{0," + (DIGITS_BEFORE_POINT + DIGITS_AFTER_POINT - 1) + "}+((\\.[0-9]{0," + (DIGITS_AFTER_POINT - 1) + "})?)||(\\.)?");
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

        Matcher matcher = mPattern.matcher(dest);
        if (!matcher.matches())
            return "";
        return null;
    }
}